package com.esl.coordinator.command;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esl.coordinator.exception.STiTEQATMELIntegrationException;
import com.esl.coordinator.util.Hex;

/**
 * @author jeffreychang ChangeRFChannelCommand per Sipix Spec
 */
class ChangeRFChannelCommand extends Command {
	static final Logger LOG = LoggerFactory
			.getLogger(ChangeRFChannelCommand.class);

	public static final String CHANGE_RF_CHANNEL_LEAD_CODE = "CC";
	public static final String CHANGE_RF_CHANNEL_LENGTH = "02";
	public static final String CHANGE_RF_CHANNEL_COMMAND_TYPE = "2F";

	private static final int EXPECTED_RESPONSE_BYTES = 4;

	private int channelNumber;

	public ChangeRFChannelCommand(int channelNumber,
			CommandReceiver commandClient) {
		super(commandClient, EXPECTED_RESPONSE_BYTES);
		this.channelNumber = channelNumber;
	}

	@Override
	public String[] buildCommand() {
		StringBuffer messageString = new StringBuffer();
		messageString.append(CHANGE_RF_CHANNEL_LEAD_CODE);
		messageString.append(CHANGE_RF_CHANNEL_LENGTH);
		messageString.append(CHANGE_RF_CHANNEL_COMMAND_TYPE);
		messageString.append(Hex.toHexString(channelNumber));

		return new String[] { messageString.toString() };
	}

	@Override
	public boolean isCommandSuccessful() {
		if (getCommandResponse() != null && getCommandResponse().length == 1) {
			if (getCommandResponse()[0].endsWith("FF")) {
				return true;
			}
		}
		return false;
	}

	public int getChannelNumber() {
		return channelNumber;
	}

	public void setChannelNumber(int channelNumber) {
		this.channelNumber = channelNumber;
	}

	public static void main(String[] args) {
		try {
			Command testCmd = STiTEQATMELCommandFactory.getInstance()
					.createRFChannelCommand(
							14,
							SocketCommandReceiver.getInstance("192.168.0.2",
									8088));
			CommandInvoker.sendCommand(testCmd);
			testCmd.isCommandSuccessful();
		} catch (STiTEQATMELIntegrationException e) {
			LOG.error("Error in test.", e);
		} catch (IOException e) {
			LOG.error("Error in test.", e);
		}
	}
}
